package com.ycg.blog.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.ycg.blog.interceptor.IpInterceptor;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author YCG
 * @date 2024-01-21 18:02
 * @description 跨域配置
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Resource
    private IpInterceptor ipInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns(
                        "https://hope-api.top/",
                        "http://8.138.133.92")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(ipInterceptor).addPathPatterns("/**");
        registry.addInterceptor(new SaInterceptor(handle -> {
                    // 过滤option方法
                    if (SaHolder.getRequest().getMethod().equals("OPTIONS")) {
                        return;
                    }
                    StpUtil.checkLogin();
                }))
                .addPathPatterns("/article/add")
                .addPathPatterns("/categories/put")
                .addPathPatterns("/categories/add")
                .addPathPatterns("/tags/put")
                .addPathPatterns("/tags/delete")
                .excludePathPatterns("/user/doLogin");
    }
}


